import com.rslai.commons.util.FileUtil;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by rslai on 2018/12/9.
 */
public class FindContent {
    String resTypePattern = ".*(?i)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|webp|jfif|tiff|dib).*"; // 资源文件（图片）类型
    String contentPattern; // 包含字符串正则

    public void findContent(List<String> findFiles, List<String> findStrs) {
        contentPattern = ".*(?i)(";
        for (String str : findStrs) {
            contentPattern = contentPattern + str + "|";
        }
        contentPattern = contentPattern.substring(0,contentPattern.length() - 1);
        contentPattern = contentPattern + ").*";

        for (String findFile : findFiles) {
            System.out.println("==================== 在指定目录查找：" + findFile);
            oneFindContent(findFile);
        }
    }

    /**
     * 在一个app中查找文字
     *
     * @param fileName
     */
    private void oneFindContent(String fileName) {
        String destPath = new FileUtil().getCanonicalPath(fileName).replace(".ipa", "").replace(".apk", "");

        FileUtil fileUtil = new FileUtil();
        List<String> files = fileUtil.listAll(destPath);
        for (String file : files) {
            if (findType(file)) {
                System.out.println("===== 在文件中查找指定字符：" + file);
                StringBuffer tmpSB = new StringBuffer();
                if (oneFindFile(file)) {
                }
            }
        }
    }

    /**
     * 在一个文件中查找字符
     * @param fileName
     * @return
     */
    private boolean oneFindFile(String fileName) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
            String tempString = null;
            // 循环读取文件
            while ((tempString = reader.readLine()) != null) {
                if (Pattern.matches(contentPattern, tempString)) {
                    System.out.println(tempString);
                }

            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ioe) {
                }
            }
        }
        return true;
    }

    /**
     * 判断文件是否是图片文件
     * @param str 文件名
     * @return {@code true} 是图片
     */
    private boolean findType(String str) {
        return !Pattern.matches(resTypePattern, str);
    }
}
